package com.mall.order.web.interceptor;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.mall.cart.service.CartService;
import com.mall.manager.pojo.TbItem;
import com.mall.manager.pojo.TbUser;
import com.mall.pojo.TaotaoResult;
import com.mall.sso.service.TokenService;
import com.mall.utils.CookieUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


/**
 * @author Administrator
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Reference
    private TokenService tokenService;

    @Reference
    private CartService cartService;


    @Value("${sso_url}")
    private String ssoUrl;

    @Value("${order_url}")
    private String orderUrl;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = CookieUtils.getCookieValue(request, "token");

        //不存在token
        if (StringUtils.isEmpty(token)) {
            //未登录跳转到登录页面,登录成功之后跳转到当前请求页面
            response.sendRedirect(ssoUrl + "/page/login?redirect=" + orderUrl + request.getRequestURI());
            return false;
        }
        //存在token,验证token是否过期
        TaotaoResult taotaoResult = tokenService.verifyToken(token);
        if (taotaoResult == null || taotaoResult.getStatus() != 200) {
            //token已经过期
            response.sendRedirect(ssoUrl + "/page/login?redirect=" + orderUrl + request.getRequestURI());
            return false;
        }
        //已经登录，请user信息放入到请求域
        TbUser user = (TbUser) taotaoResult.getData();
        request.setAttribute("User", user);
        //如果cookie中含有订单信息将其合并到服务端
        String cart = CookieUtils.getCookieValue(request, "cart", true);
        List<TbItem> cookieItems = JSONArray.parseArray(cart, TbItem.class);
        //合并数据
        cartService.mergeItems(cookieItems, user.getId());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
